package com.ctg.payroll2.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.WebApplicationContext;

import com.ctg.tax.util.TaxUtils;

@SuppressWarnings("unchecked")
public class ControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 996718938019849409L;
	
	private static Logger logger = Logger.getLogger(ControllerServlet.class);

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		logger = Logger.getLogger(this.getClass().getName());
		try {
			ServletContext context = this.getServletContext();
			//initLog4j(context);
			initTax(context);
			//test(context);
		} catch (Exception e) {
			logger.error("Unexpected error encountered: ", e);
			e.printStackTrace();
		}
	}

	public void initLog4j(ServletContext context) throws Exception {
		// prepare log4j config path
		String log4jConfigFilePath = getInitParameter("Log4jConfigFile");
		File log4jConfigFile = new File(context
				.getRealPath(log4jConfigFilePath));

		/***
		 * Init all resource(s)
		 */
		// init log4j
		Properties log4jProperties = new Properties();
		try {
			FileInputStream fin = new FileInputStream(log4jConfigFile);
			log4jProperties.load(fin);
		} catch (Exception e) {
			// do nothing, check if empty is implemented in below
		}

		if (log4jProperties.size() > 0) {
			// Successfully loaded , config each file appender to has log
			Enumeration keys = log4jProperties.keys();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				if (key.endsWith(".File")) {
					String value = log4jProperties.getProperty(key);
					value = context.getRealPath(value);
					log4jProperties.setProperty(key, value);
				}
			}
			PropertyConfigurator.configure(log4jProperties);
		} else {
			// Fail to load config file or config file is empty, or improperly
			// formatted. Use default log4j configuration instead.
			BasicConfigurator.configure();
			logger.warn("Unable to access log4j config file.");
		}
	}
	
	/**
	 * 初始化税率表
	 * @param context
	 * @throws Exception
	 */
	public void initTax(ServletContext context) throws Exception {
		TaxUtils.resetTaxes(context);
	}
	
	public void destroy() {
	}
}
